/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.ValidationTests.ACATS_3_0.Support;
using NUnit.Framework;
using Rhino.Mocks;

namespace NTasking.ValidationTests.ACATS_3_0.C9
{

    [TestFixture(Description = "")]
    public class C93004D : ValidationTest
    {

        private static T2[] t2;


        private class T0 : ValidationTestTask
        {

            [Entry]
            internal Action E { get; private set; }


            internal T0(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void DeclarativePart()
            {
            }


            protected override void Body()
            {
                Accept(E);
            }

        }


        private class T1 : ValidationTestTask
        {

            internal T1(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                Ada.Declare(() =>
                {
                    new T1Bis(Result);
                },
                Begin: () =>
                {
                });

                t2[3].E(); // t2 is now terminated

                Console.WriteLine("RENDEZVOUS COMPLETED WITHOUT ERROR - T1");
                Result.TestFailed();
            }
            protected override void Exception(Exception ex)
            {
                if (ex is TaskingError)
                {
                    Console.WriteLine("T1 body caught TaskingError");
                }
                else
                {
                    Console.WriteLine("ABNORMAL EXCEPTION - T1");
                    Console.WriteLine(ex);
                    Result.TestFailed();
                }
            }

        }


        private class T1Bis : ValidationTestTask
        {

            internal T1Bis(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                try
                {
                    t2[3].E(); // t2 is now terminated

                    Console.WriteLine("RENDEZVOUS COMPLETED WITHOUT ERROR - T1BIS");
                    Result.TestFailed();
                }
                catch (TaskingError)
                {
                    Console.WriteLine("T1Bis body caught TaskingError");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ABNORMAL EXCEPTION - T1");
                    Console.WriteLine(ex);
                    Result.TestFailed();
                }
            }

        }


        private class T2 : ValidationTestTask
        {

            [Entry]
            internal Action E { get; private set; }


            internal T2(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void DeclarativePart()
            {
                throw new NullReferenceException();
            }


            protected override void Body()
            {
                Console.WriteLine("T2 ACTIVATED OK");
                Result.TestFailed();
            }

        }


        private class T3 : ValidationTestTask
        {

            [Entry]
            internal Action E { get; private set; }


            internal T3(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                Accept(E);
            }

        }


        [Test(Description =
            "CHECK THAT WHEN AN EXCEPTION IS RAISED DURING THE ACTIVATION OF A" +
            "TASK, OTHER TASKS ARE UNAFFECTED." +
            "" +
            "THE ENCLOSING BLOCK RECEIVES TASKING_ERROR." +
            "" +
            "THIS TEST CHECKS THE CASE IN WHICH SOME OF THE OTHER TASKS ARE " +
            "PERHAPS ACTIVATED BEFORE THE EXCEPTION OCCURS AND SOME TASKS ARE " +
            "PERHAPS ACTIVATED AFTER." +
            "" +
            "CHECK THAT TASKS WAITING ON ENTRIES OF SUCH TASKS RECEIVE" +
            "TASKING_ERROR")]
        public void Test()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();
            T0 t0 = null;
            T1 t1;
            T3 t3 = null;

            Ada.Declare(() =>
            {
                t1 = new T1(result);
            },
            Begin: outer =>
            {
                Ada.Declare(() =>
                {
                    t0 = new T0(result);
                    t2 = new T2[] { new T2(result), new T2(result), new T2(result), new T2(result) };
                    t3 = new T3(result);

                    // Setup text expectations

                    Expect.Call(result.TestFailed).Repeat.Never();
                    Mocks.ReplayAll();

                    // Start test execution
                },
                Begin: inner =>
                {
                    // Prematurely start t1 to force t1 and t1bis to wait on t2.E
                    outer.Activate();

                    // Ensure t1 and t1bis is waiting on t2 entry
                    Ada.Delay(Impdef.SwitchToNewTask);

                    try
                    {
                        inner.Activate();

                        t0.E(); // Cleanup
                        t3.E(); // Cleanup

                        Console.WriteLine("NO EXCEPTION RAISED");
                        result.TestFailed();
                    }
                    catch (NullReferenceException)
                    {
                        Console.WriteLine("NullReferenceException thrown");
                        result.TestFailed();
                    }
                    catch (TaskingError)
                    {
                        try
                        {
                            t0.E();
                            t3.E();
                        }
                        catch (TaskingError)
                        {
                            Console.WriteLine("T0 or T3 NOT ACTIVATED");
                            result.TestFailed();
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("T0 or T3 CALL THREW EXCEPTION");
                            result.TestFailed();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("ABNORMAL EXCEPTION IN MAIN-2");
                        result.TestFailed();
                    }
                });
            });
        }

    }

}
